package healththink
import grails.plugins.springsecurity.*

class FacilityController {
    def springSecurityService
  
    @Secured(['ROLE_OWNER', 'ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def scaffold = true

    def mobileService
    
    def afterInterceptor = [action: this.&handleMobile]
	 
    private handleMobile(model, modelAndView) {
       
        
            if (modelAndView && mobileService.detect(request)) {

                modelAndView.viewName = '/mobile/' + modelAndView.viewName          

            }
	 
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def index() { 
        redirect(action: "list")
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def facilityList = {
        def facilityList = Facility.list()
        [facilityList: facilityList]
    }
    
   @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def search = {
        
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def searchResults = {
        def q = Facility.createCriteria()
        def facilitiesFound = q.listDistinct() {
            and {
                params.each {field, value ->
                    if(field == 'facilitySearch' && value){
                        ilike("name", "%" + value + "%")
                    }   
                    else if(field == 'type' && value){
                        eq('facilityType', FacilityType.valueOf(value))
                    }
                }
            }
        }
        if(params.distance !="" && params.facilitySearch == "" && params.type == ""){
            facilitiesFound = Facility.list()
        }
        if(params.distance != ""){
            int dist = Integer.parseInt(params.distance)
            facilitiesFound.each{
                if(it.getDistance(Double.parseDouble(params.latitude), Double.parseDouble(params.longitude))>dist){
                    facilitiesFound-=it
                }
            }
        }	
        return [facilities: facilitiesFound, term: params.facilitySearch]
    }
    
    @Secured(['ROLE_OWNER', 'IS_AUTHENTICATED_FULLY'])
    def register = {
        if(!params.register)return
        
        if(params){
            def facility = new Facility(params)
            def telephoneNumber = new TelephoneNumber(params)
            if(telephoneNumber.number!=null){
                facility.addToPhones(telephoneNumber)
            }
            if(facility.validate()){
                facility.save()
                if(mobileService.detect(request)){
                    forward action: "view", params: [name: facility.name]
                }else{
                    redirect(action: "view", params: [name: facility.name])
                }
            }else{
                return [facility: facility]
            }
        }else{
            [facility: facility]
        }
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def view  = {
        def facility = Facility.findByName(params.name)
        if(facility){
            session.name = facility.name
        }else{
            facility = Facility.findByName(session.name)
        }
        def forumList = Forum.findAllByFacility(facility, [max: 10, sort: "datePosted", order: "desc"])
        [facility: facility, forumList: forumList]

    }
    
    @Secured(['ROLE_OWNER', 'ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def editNumbers = {
        if(!params.phone){
            def facility = Facility.findByName(params.name)
            [facility: facility]
        }else{
            def facility = Facility.findByName(params.name)
            def phoneNumber = new TelephoneNumber(params)
            facility.addToPhones(phoneNumber)
            phoneNumber.save()
            if(mobileService.detect(request)){
                forward action: "view", params: [name: facility.name]
            }else{
                redirect(action: "view", params: [name: facility.name])
            }
        }
    }
    
    @Secured(['ROLE_OWNER', 'ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def deleteNumber = {
        def phoneNumber = TelephoneNumber.findById(params.id)
        def facility = Facility.findByName(params.name)
        facility.removeFromPhones(phoneNumber)
        phoneNumber.delete()
        if(mobileService.detect(request)){
            forward action: "editNumbers", params: [name: params.name]
        }else{
            redirect(action: "view", params: [name: params.name])
        }
    }
    
    @Secured(['ROLE_OWNER', 'ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def editGeneralInfo = {
        if(!params.update){
            def facility = Facility.findByName(params.name)
            [facility: facility]
        }else{
            def facility = Facility.findByName(params.name)
            facility.properties = params
            facility.facilitySite?.properties = params
            facility.primaryAddress?.properties = params
            if(mobileService.detect(request)){
                forward action: "view", params: [name: params.name]
            }else{
                redirect(action: "view", params: [name: params.name])
            }
        }
    }
    
    @Secured(['ROLE_OWNER','ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def editAttributes = {
        def facility = Facility.findByName(params.name)
        def facilityAttributeNames = []
        facility.facilityAttributes.each{
            facilityAttributeNames.add(it.attribute.name)
        }
        def attributeList = Attribute.list()
        def attributeNames = []
        for(int i=0; i<attributeList.size(); i++){
            if(!facilityAttributeNames.contains(attributeList.get(i).name)){
                attributeNames.add(attributeList[i].name)
            }
        }
        [facility: facility, facilityAttributeNames: facilityAttributeNames, attributeNames: attributeNames]
    }
    
    @Secured(['ROLE_OWNER','ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def addAttribute = {
        def facility = Facility.findByName(params.name)
        def attribute = Attribute.findByName(params.attrName)
        FacilityAttributeLink.link(attribute, facility)
        if(mobileService.detect(request)){
            forward action: "editAttributes", params: [name: facility.name]
        }else{
            redirect(action: "editAttributes", params: [name: facility.name])
        }
    }
    
    @Secured(['ROLE_OWNER','ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def removeAttribute = {
        def facility = Facility.findByName(params.name)
        def attribute = Attribute.findByName(params.attrName)
        FacilityAttributeLink.unlink(attribute, facility)
        if(mobileService.detect(request)){
            forward action: "editAttributes", params: [name: facility.name]
        }else{
            redirect(action: "editAttributes", params: [name: facility.name])
        }
    }
    
    @Secured(['ROLE_OWNER','ROLE_CONTRIBUTOR','ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def rateAttribute = {
        def facility = Facility.findByName(params.facilityName)
        def attribute = Attribute.findByName(params.attrName)
        def attrLink = FacilityAttributeLink.findByAttributeAndFacility(attribute, facility)
        def linkRating = new FacilityAttributeRating(rating: params.rating as int)
        attrLink.addToFacilityAttributeRatings(linkRating)
        if(mobileService.detect(request)){
            forward action: "view", params: [name: facility.name]
        }else{
            redirect(action: "view", params: [name: facility.name])
        }
    }
    
    @Secured(['ROLE_OWNER','ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def editGroups = {
        def facility = Facility.findByName(params.name)
        def facilityGroupNames = []
        facility.facilityGroups.each{
            facilityGroupNames.add(it.facilityGroup.groupName)
        }
        def groupList = FacilityGroup.list()
        def groupNames = []
        for(int i=0; i<groupList.size(); i++){
            if(!facilityGroupNames.contains(groupList.get(i).groupName)){
               groupNames.add(groupList[i].groupName)
            }
        }
        [facility: facility, facilityGroupNames: facilityGroupNames, groupNames: groupNames]
    }
    
    @Secured(['ROLE_OWNER', 'IS_AUTHENTICATED_FULLY'])
    def addGroup = {
        def facility = Facility.findByName(params.name)
        def group = FacilityGroup.findByGroupName(params.groupName)
        FacilityGroupLink.link(group, facility)
        if(mobileService.detect(request)){
            forward action: "editGroups", params: [name: facility.name]
        }else{
            redirect(action: "editGroups", params: [name: facility.name])
        }
    }
    
    @Secured(['ROLE_OWNER', 'IS_AUTHENTICATED_FULLY'])
    def removeGroup = {
        def facility = Facility.findByName(params.name)
        def group = FacilityGroup.findByGroupName(params.groupName)
        FacilityGroupLink.unlink(group, facility)
        if(mobileService.detect(request)){
            forward action: "editGroups", params: [name: facility.name]
        }else{
            redirect(action: "editGroups", params: [name: facility.name])
        }
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def viewForums = {
        def facility = Facility.findByName(params.name)
        def forumList = Forum.findAllByFacility(facility, [sort: "datePosted", order: "desc"])
        [facility: facility, forumList: forumList]
    }
    
    @Secured(['ROLE_OWNER','ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def deleteForum = {
        def facility = Facility.findByName(params.name)
        def forum = Forum.findByFacilityAndTopic(facility, params.topic)
        facility.removeFromForums(forum)
        forum.delete()
        redirect(action: "view", params: [name: facility.name])
    }
}